package repository

import (
	"context"
	"gorm.io/gorm/clause"
	"onvif_server/internal/model"
)

type SettingRepository interface {
	Create(ctx context.Context, m *model.Setting) error
	Update(ctx context.Context, m *model.Setting, fields ...string) error
	GetByKey(ctx context.Context, key string) (m *model.Setting, err error)
	GetAll(ctx context.Context) (ms []*model.Setting, err error)
	DeleteByKey(ctx context.Context, id []int) error
	Store(ctx context.Context, m *model.Setting) error
}

func NewSettingRepository(r *Repository) SettingRepository {
	return &settingRepository{
		Repository: r,
	}
}

type settingRepository struct {
	*Repository
}

func (r *settingRepository) Create(ctx context.Context, m *model.Setting) error {
	return r.DB(ctx).Create(m).Error
}

func (r *settingRepository) Update(ctx context.Context, m *model.Setting, fields ...string) error {
	_db := r.DB(ctx)
	if len(fields) > 0 {
		_db = _db.Select(fields)
	}
	return _db.Where("key = ?", m.Key).Updates(m).Error
}

func (r *settingRepository) GetByKey(ctx context.Context, key string) (m *model.Setting, err error) {
	err = r.DB(ctx).Where("key = ?", key).First(&m).Error
	return
}

func (r *settingRepository) GetAll(ctx context.Context) (ms []*model.Setting, err error) {
	err = r.DB(ctx).Find(&ms).Error
	return
}

func (r *settingRepository) DeleteByKey(ctx context.Context, id []int) error {
	return r.DB(ctx).Delete(&model.Camera{}, id).Error
}

func (r *settingRepository) Store(ctx context.Context, m *model.Setting) error {
	return r.DB(ctx).Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "key"}},
		DoUpdates: clause.AssignmentColumns([]string{"val", "sort", "name", "type", "remark"}),
	}).Create(&m).Error
}
